package org.jeecgframework.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.mybatis.ext.WiseCoreService;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.*;
import org.jeecgframework.web.service.impl.ZyTimeTaskForIntallRecordServiceImpl;
import org.jeecgframework.web.service.impl.ZyTimeTaskOfProcurementServiceImpl;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.FileBean;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 服务合同信息
 * @date 2017-12-22 14:46:11
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsContractController")
public class CbsContractController extends BaseController {
        /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger ( CbsContractController.class );
    //获取系统当前时间
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar c = Calendar.getInstance();
    java.util.Date date = c.getTime();
    String s = sdf.format(date);

    @Autowired
    private CbsContractServiceI cbsContractService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ZyCommonService zyCommonService;
    @Autowired
    private CbsContractMcEquipmentServiceI cbsContractMcEquipmentServiceI;
    @Autowired
    private ZyEquipmentSpareServiceI zyEquipmentSpareService;
    @Autowired
    private CbsContractSlaServiceI cbsContractSlaService;
    @Autowired
    private WiseCoreService wiseCoreService;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 服务合同信息列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsContract")
    public ModelAndView cbsContract(HttpServletRequest request) {
        String code = request.getParameter("code");
        if(StringUtil.isNotEmpty(code)){
            request.setAttribute ( "code", code );
        }
        return new ModelAndView ( "com/zybk/cbscontract/cbsContractList" );
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsContractEntity cbsContract, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery ( CbsContractEntity.class, dataGrid );
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql ( cq, cbsContract, request.getParameterMap () );
        try {
            //自定义追加查询条件

        } catch (Exception e) {
            throw new BusinessException ( e.getMessage () );
        }
        cq.add ();
        this.cbsContractService.getDataGridReturn ( cq, true );
        /*List<CbsContractEntity> results = dataGrid.getResults();
        String contractDate = null;
        for(int i = 0;i<results.size();i++){
            if(results.get(i).getContractDate()!=null){
                contractDate = results.get(i).getContractDate().toString().substring(0,10);
                results.get(i).setContractDate(Date.valueOf(contractDate));
            }
        }*/
        TagUtil.datagrid ( response, dataGrid );
    }

    @RequestMapping(params = "datagridMc")
    public void datagridMc(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();

        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i]);
                    }
                }
            }
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("serviceEndDate_begin")))) {
            param.put("serviceEndDate_begin", oConvertUtils.getString(param.get("serviceEndDate_begin")) + " 00:00:00");
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("serviceEndDate_end")))) {
            param.put("serviceEndDate_end", oConvertUtils.getString(param.get("serviceEndDate_end")) + " 23:59:59");
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("contractDate_begin")))) {
            param.put("contractDate_begin", oConvertUtils.getString(param.get("contractDate_begin")) + " 00:00:00");
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("contractDate_end")))) {
            param.put("contractDate_end", oConvertUtils.getString(param.get("contractDate_end")) + " 23:59:59");
        }
        wiseCoreService.selectDataGrid("selectAll", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }
    /**
     * 服务合同信息新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsContractEntity cbsContract, HttpServletRequest req) {
        if (StringUtil.isNotEmpty ( cbsContract.getId () )) {
            cbsContract = cbsContractService.getEntity ( CbsContractEntity.class, cbsContract.getId () );
            req.setAttribute ( "cbsContractPage", cbsContract );
        }
        String code = req.getParameter("code");
        String slaId = req.getParameter("slaId");
        String contractId = req.getParameter("contractId");
        if(slaId!=null){
            String[] slaIds = slaId.split(",");
            req.setAttribute("slaId",slaIds);
            List<String> slaIdListbySql = systemService.findListbySql("select cs.id from cbs_contract_sla cs LEFT JOIN sla_contract c ON cs.id=c.sla_Id LEFT JOIN cbs_contract cc ON cc.id=c.contract_id where cc.id='" + contractId + "'");
            req.setAttribute("slaIdListbySql", slaIdListbySql);
            List<SlaContractEntity> sItemList = systemService.findHql("from SlaContractEntity where contractId='" + contractId+"'");
            req.setAttribute("sItemList", sItemList);
        }
        req.setAttribute ( "contractId", contractId );
        req.setAttribute("code",code);

        List<TSDepart> tsDeparts = systemService.findHql("from TSDepart where orgType = ?", StaticValue.DIC_ORG_TYPE_THIRD_PARTY);
        req.setAttribute("tsDeparts", tsDeparts);
        //SLA条款信息
        List<CbsContractSlaEntity> slaList = systemService.findHql("from CbsContractSlaEntity where isUse = " + StaticValue.DIC_TRUE_OR_FALSE_NUM_1 + "");
        if(slaList != null){
            for(int i = 0;i<slaList.size();i++){
                String serviceItem = slaList.get(i).getServiceItem();
                slaList.get(i).setServiceItems(serviceItem.split(","));
            }
            req.setAttribute("slaList", slaList);
        }
//        return new ModelAndView ( "com/zybk/cbscontract/cbsContract-add" );
        return new ModelAndView ( "com/zybk/cbscontract/cbsContractCreate" );
    }


    /**
     * 添加服务合同信息
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(HttpServletRequest request) {
        AjaxJson j = new AjaxJson ();
        message = "服务合同信息添加成功";
        j.setSuccess(true);
        try {
            String id = request.getParameter("id");
            String contractCode = request.getParameter("contractCode");
            String contractType = request.getParameter("contractType");
            String contractName = request.getParameter("contractName");
            String clientName = request.getParameter("clientName");
            String contractDate = request.getParameter("contractDate");
            String contractSignUser = request.getParameter("contractSignUser");
            String memo = request.getParameter("memo");
            String repairProvider = request.getParameter("repairProvider");
            String repairType = request.getParameter("repairType");
            String inspectionProvider = request.getParameter("inspectionProvider");
            String inspectionType = request.getParameter("inspectionType");
            String serviceCommitment = request.getParameter("serviceCommitment");
            String[] serviceItems = request.getParameterValues("serviceItems");
            String[] ids = request.getParameterValues("ids");
            String[] contain = request.getParameterValues("contain");
            String[] serviceName = request.getParameterValues("serviceName");
            String[] description = request.getParameterValues("description");
            String[] supplement = request.getParameterValues("supplement");
            StringBuffer sb = new StringBuffer();
            sb.append("select count(1) as total from cbs_contract t where t.contract_code = '"+contractCode+"'");
            if(StringUtil.isNotEmpty(id)){
                sb.append(" and t.id != '"+id+"'");
            }
            int total = zyCommonService.getCountBySql(sb.toString());
            if(total > 0){
                message = "当前合同编号已存在";
                j.setSuccess(false);
            }else{
                CbsContractEntity cbsContract = new CbsContractEntity();
                cbsContract.setContractCode(contractCode);
                cbsContract.setContractType(contractType);
                cbsContract.setContractName(contractName);
                cbsContract.setClientName(clientName);
                if(contractDate!=null&!"".equals(contractDate)){
                    cbsContract.setContractDate(Date.valueOf(contractDate));
                }
                cbsContract.setContractSignUser(contractSignUser);
                cbsContract.setMemo(memo);
                cbsContract.setRepairProvider(repairProvider);
                cbsContract.setRepairType(Integer.valueOf(repairType));
                cbsContract.setInspectionProvider(inspectionProvider);
                cbsContract.setInspectionType(Integer.valueOf(inspectionType));
                cbsContract.setStatus(0);
                cbsContract.setEditStatus(1);
                cbsContract.setServiceCommitment(serviceCommitment);
                cbsContractService.save ( cbsContract );
                systemService.addLog ( message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO );
                //sla
                //List<CbsContractEntity> cbsContractHql = systemService.findHql("from CbsContractEntity order by createDate desc");
                StringBuffer slaIdBuffer = new StringBuffer();
                StringBuffer serviceNameBuffer = new StringBuffer();
                StringBuffer descriptionBuffer = new StringBuffer();
                StringBuffer supplementBuffer = new StringBuffer();
                if(StringUtil.isNotEmpty(ids)){
                    for(int i = 0;i<ids.length;i++){
                        SlaContractEntity slaContract = new SlaContractEntity();
                        slaContract.setContractId(cbsContract);
                        slaContract.setsItem(serviceItems[i]);
                        CbsContractSlaEntity cbsContractSlaServiceEntity = cbsContractSlaService.getEntity(CbsContractSlaEntity.class, ids[i]);
                        if(Integer.valueOf(contain[i])==1){
                            slaContract.setSlaId(cbsContractSlaServiceEntity);
                            systemService.save(slaContract);
                        }
                        slaIdBuffer.append(ids[i]+",");
                        serviceNameBuffer.append(serviceName[i]+" "+",");
                        descriptionBuffer.append(description[i]+" "+",");
                        supplementBuffer.append(supplement[i]+" "+",");
                    }
                    cbsContract.setSlaId(slaIdBuffer.toString().substring(0,slaIdBuffer.length()-1));
                    cbsContract.setServiceName(serviceNameBuffer.toString().substring(0,serviceNameBuffer.toString().length()-1));
                    cbsContract.setDescription(descriptionBuffer.toString().substring(0,descriptionBuffer.toString().length()-1));
                    cbsContract.setSupplement(supplementBuffer.toString().substring(0,supplementBuffer.toString().length()-1));
                }
                systemService.saveOrUpdate(cbsContract);
            }
        } catch (Exception e) {
            e.printStackTrace ();
            message = "服务合同信息添加失败";
            j.setSuccess(false);
            throw new BusinessException ( e.getMessage () );
        }
        j.setMsg ( message );
        return j;
    }

    /**
     * 服务合同信息编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsContractEntity cbsContract, HttpServletRequest req) {
        if (StringUtil.isNotEmpty ( cbsContract.getId () )) {
            cbsContract = cbsContractService.getEntity ( CbsContractEntity.class, cbsContract.getId () );
            req.setAttribute ( "cbsContractPage", cbsContract );
            List<TSDepart> tsDeparts = systemService.findHql("from TSDepart where orgType = ?", StaticValue.DIC_ORG_TYPE_THIRD_PARTY);
            req.setAttribute("tsDeparts", tsDeparts);
            //SLA条款信息
            String[] slaIdsplit={};
            if(cbsContract.getSlaId()!=null){
                slaIdsplit = cbsContract.getSlaId().split(",");
            }
            String[] serviceNameSplit = {};
            if(cbsContract.getServiceName()!=null){
                serviceNameSplit = cbsContract.getServiceName().split(",");
            }
            String[] descriptionSplit = {};
            if(cbsContract.getDescription()!=null){
                descriptionSplit = cbsContract.getDescription().split(",");
            }
            String[] supplementSplit = {};
            if(cbsContract.getSupplement()!=null){
                supplementSplit = cbsContract.getSupplement().split(",");
            }
            String slaId = cbsContract.getSlaId();
            /*List<CbsContractSlaEntity> slaList = new ArrayList<>();
            if(StringUtil.isNotEmpty(slaId)){
                String[] slaSplit = slaId.split(",");
                for(int i = 0;i<slaSplit.length;i++){
                    CbsContractSlaEntity cbsContractSla = systemService.getEntity(CbsContractSlaEntity.class, slaSplit[i]);
                    slaList.add(cbsContractSla);
                }
            }*/
            List<CbsContractSlaEntity> slaList = systemService.findHql("from CbsContractSlaEntity where isUse = " + StaticValue.DIC_TRUE_OR_FALSE_NUM_1+"");
            List<String> slaIdListbySql = systemService.findListbySql("select cs.id from cbs_contract_sla cs LEFT JOIN sla_contract c ON cs.id=c.sla_Id LEFT JOIN cbs_contract cc ON cc.id=c.contract_id where cc.id='" + cbsContract.getId() + "'");
            req.setAttribute("slaIdListbySql", slaIdListbySql);
            List<SlaContractEntity> sItemList = systemService.findHql("from SlaContractEntity where contractId='" + cbsContract.getId()+"'");
            req.setAttribute("sItemList", sItemList);
            if(slaList != null){
                for(int i = 0;i<slaList.size();i++){
                    String serviceItem = slaList.get(i).getServiceItem();
                    slaList.get(i).setServiceItems(serviceItem.split(","));
                    for(int j = 0;j<slaIdsplit.length;j++){
                        if(slaList.get(i).getId().equals(slaIdsplit[j])){
                            slaList.get(i).setsName(serviceNameSplit[j]);
                            slaList.get(i).setDescrip(descriptionSplit[j]);
                            slaList.get(i).setSupple(supplementSplit[j]);
                        }
                    }
                }
                req.setAttribute("slaList", slaList);
            }
        }
        //MC条款信息
        List<CbsContractMcEquipmentEntity> mcList = systemService.findHql("from CbsContractMcEquipmentEntity where contractCode = '" + cbsContract.getContractCode() + "'");
        if(mcList != null){
            req.setAttribute("mcList", mcList);
        }
        for(int i = 0;i<mcList.size();i++){
            if(mcList.get(i).getStatus()!=1){
                req.setAttribute("code", 1);
            }
        }
        return new ModelAndView ( "com/zybk/cbscontract/cbsContract-update" );
    }

    /**
     * 更新服务合同信息
     *
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(HttpServletRequest request) throws Exception {
        CbsContractEntity cbsContract = new CbsContractEntity();
        CbsContractMcEquipmentEntity cbsContractMcEquipmentEntity = new CbsContractMcEquipmentEntity();
        AjaxJson j = new AjaxJson ();
        String id = request.getParameter("id");
        String[] mids = request.getParameterValues("mid");
        String[] serviceItems = request.getParameterValues("serviceItems");
        String re = request.getParameter("re");
        String cancelDes = request.getParameter("cancelDes");
        if("撤销".equals(re)){
            if("".equals(cancelDes)||cancelDes==null){
                message = "请填写撤销原因";
                j.setSuccess(false);
                j.setMsg(message);
                return j;
            }
            CbsContractEntity t = cbsContractService.get ( CbsContractEntity.class, id );
            cbsContract.setStatus(1);
            cbsContract.setCancelDes(cancelDes);
            cbsContractMcEquipmentServiceI.updateBySqlString("update cbs_contract_mc_equipment set status='4' where contract_code='"+t.getContractCode()+"'");
            try {
                message = "服务合同已撤销";
                j.setSuccess(true);
                MyBeanUtils.copyBeanNotNull2Bean ( cbsContract, t );
                cbsContractService.saveOrUpdate ( t );
                systemService.addLog ( message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO );
            } catch (Exception e) {
                e.printStackTrace ();
                message = "服务合同撤销失败";
                throw new BusinessException ( e.getMessage () );
            }
            j.setMsg ( message );
            return j;
        }else{
            String contractCode = request.getParameter("contractCode");
            String contractType = request.getParameter("contractType");
            String contractName = request.getParameter("contractName");
            String clientName = request.getParameter("clientName");
            String payCircle = request.getParameter("payCircle");
            String contractDate = request.getParameter("contractDate");
            if (contractDate!=null&!"".equals(contractDate)){
                contractDate=contractDate.substring(0,10);
            }
            String payStatus = request.getParameter("payStatus");
            String contractSignUser = request.getParameter("contractSignUser");
            String memo = request.getParameter("memo");
            String payDate = request.getParameter("payDate");
            if (payDate!=null&!"".equals(payDate)){
                payDate=payDate.substring(0,10);
            }
            String repairProvider = request.getParameter("repairProvider");
            String repairType = request.getParameter("repairType");
            String inspectionProvider = request.getParameter("inspectionProvider");
            String inspectionType = request.getParameter("inspectionType");
            String serviceCommitment = request.getParameter("serviceCommitment");
            String[] serviceStartDates = request.getParameterValues("serviceStartDate");
            if (serviceStartDates!=null){
                for(int i=0;i<serviceStartDates.length;i++){
                    serviceStartDates[i] = serviceStartDates[i].substring(0,10);

                }
            }
            String[] serviceEndDates = request.getParameterValues("serviceEndDate");
            if (serviceEndDates!=null){
                for(int i=0;i<serviceEndDates.length;i++){
                    serviceEndDates[i] = serviceEndDates[i].substring(0,10);
                }
            }
            String[] mcCodes = request.getParameterValues("mcCode");
            if (mcCodes!=null){
                for(int i=0;i<mcCodes.length;i++){
                    cbsContractMcEquipmentEntity.setServiceStartDate(serviceStartDates[i]);
                    cbsContractMcEquipmentEntity.setServiceEndDate((serviceEndDates[i]));
                    cbsContractMcEquipmentEntity.setMcCode(mcCodes[i]);
                    CbsContractMcEquipmentEntity t1 = cbsContractService.get ( CbsContractMcEquipmentEntity.class, mids[i] );
                    if(t1!=null){
                        MyBeanUtils.copyBeanNotNull2Bean ( cbsContractMcEquipmentEntity, t1 );
                        cbsContractMcEquipmentServiceI.saveOrUpdate(t1);
                    }
                }
            }
            String[] supplements = request.getParameterValues("supplements");
            if(StringUtil.isNotEmpty(supplements)){
            StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0;i<supplements.length;i++){
                    stringBuffer.append("," + supplements[i]);
                }
                String substring = stringBuffer.toString().substring(1, stringBuffer.toString().length());
                cbsContract.setSupplement(substring);
            }
            cbsContract.setContractCode(contractCode);
            cbsContract.setContractType(contractType);
            cbsContract.setContractName(contractName);
            cbsContract.setClientName(clientName);
            if (contractDate!=null&!"".equals(contractDate)){
                cbsContract.setContractDate(Date.valueOf(contractDate));
            }
            if (payDate!=null&!"".equals(payDate)){
                cbsContract.setPayDate(Date.valueOf(payDate));
            }
            cbsContract.setPayStatus(Integer.valueOf(payStatus));
            cbsContract.setContractSignUser(contractSignUser);
            cbsContract.setMemo(memo);
            cbsContract.setPayCircle(payCircle);
            cbsContract.setRepairProvider(repairProvider);
            cbsContract.setRepairType(Integer.valueOf(repairType));
            cbsContract.setInspectionProvider(inspectionProvider);
            cbsContract.setInspectionType( Integer.valueOf(inspectionType));
            cbsContract.setServiceCommitment(serviceCommitment);
            if(mids!=null){
                for (int i=0;i<mids.length;i++){
                    cbsContractMcEquipmentEntity.setId(mids[i]);
                }
            }
            message = "服务合同信息更新成功";
            j.setSuccess(true);
            CbsContractEntity t = cbsContractService.get ( CbsContractEntity.class, id );
            MyBeanUtils.copyBeanNotNull2Bean ( cbsContract, t );
            cbsContractService.saveOrUpdate ( t );
            //更新SLA
            try {
            String[] contain = request.getParameterValues("contain");
            String[] slaIds = request.getParameterValues("slaIds");
            systemService.updateBySqlString("delete from sla_contract where contract_id='"+t.getId()+"'");
            if(StringUtil.isNotEmpty(slaIds)){
                for(int i = 0;i<slaIds.length;i++){
                    CbsContractSlaEntity cbsContractSlaServiceEntity = cbsContractSlaService.getEntity(CbsContractSlaEntity.class, slaIds[i]);
                    SlaContractEntity slaContract = new SlaContractEntity();
                    cbsContractSlaServiceEntity.setContain(Integer.valueOf(contain[i]));
                    slaContract.setsItem(serviceItems[i]);
                    if(Integer.valueOf(contain[i])==1){
                        slaContract.setSlaId(cbsContractSlaServiceEntity);
                        slaContract.setContractId(t);
                        systemService.save(slaContract);
                    }
                    cbsContractSlaService.saveOrUpdate(cbsContractSlaServiceEntity);
                }
            }
                systemService.addLog ( message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO );
            } catch (Exception e) {
                e.printStackTrace ();
                message = "服务合同信息更新失败";
                throw new BusinessException ( e.getMessage () );
            }
            j.setMsg ( message );
            return j;
            }
        }


    /**
     * 校验表单信息
     * @return
     */
    @RequestMapping(params = "checkInfo")
    @ResponseBody
    public ValidForm checkInfo(@RequestParam(value="param",defaultValue="")String param,
                               @RequestParam(value="id",defaultValue="")String id) {
        ValidForm vf = new ValidForm();
        StringBuffer sb = new StringBuffer();
        sb.append("select count(1) as total from cbs_contract t where t.contract_code = '"+param+"'");
        if(StringUtil.isNotEmpty(id)){
            sb.append(" and t.id != '"+id+"'");
        }
        int total = zyCommonService.getCountBySql(sb.toString());
        if(total > 0){
            vf.setStatus(ValidForm.N);
            vf.setInfo("当前合同编号已存在");
        }
        return vf;
    }


    /**
     * 选择合同模板
     * @param cbsContract
     * @param req
     * @return
     */
    @RequestMapping(params = "selectContractTemplate")
    public ModelAndView selectContractTemplate(CbsContractEntity cbsContract, HttpServletRequest req) {
        //SLA条款信息
        List<CbsContractEntity> contractList = systemService.findHql("from CbsContractEntity where status = " + StaticValue.CBS_CONTRACT_State_0 + " " +
                "and contractType = '"+StaticValue.CBS_CONTRACT_TYPE_MB+"'");
        if(contractList != null){
            req.setAttribute("contractList", contractList);
        }
        return new ModelAndView ( "com/zybk/cbscontract/cbsContractSelect" );
    }
    /*
    * 选择某一模板合同后，SLA条款的显示改为与模板合同一致
    * */
    @RequestMapping(params = "choose")
    @ResponseBody
    public List<String> choose(HttpServletRequest req) {
       // Map<String, Object> map = new HashMap<>();
        String contractId = req.getParameter("id");
        List<String> slaIdList = systemService.findListbySql("select ccs.id from cbs_contract_sla ccs LEFT JOIN sla_contract c ON ccs.id=c.sla_Id LEFT JOIN cbs_contract cc ON cc.id=c.contract_Id WHERE cc.id='" + contractId + "'");
        /*List<SlaContractEntity> sItemList = new ArrayList<SlaContractEntity>();
        List<String> slaIds = new ArrayList<String>();
        if(slaIdList.size()!=0){
            sItemList = systemService.findHql("from SlaContractEntity where contractId='" + contractId+"'");
            slaIds = systemService.findListbySql("select id from cbs_contract_sla");
        }
        map.put("slaIdList",slaIdList);
        map.put("sItemList",sItemList);
        map.put("slaIds",slaIds);*/
        return slaIdList;
    }
    /**
     * 修改确认
     * @return
     */
    @RequestMapping(params = "realUpdate")
    public ModelAndView realUpdate() {
        /*//SLA条款信息
        List<CbsContractEntity> contractList = systemService.findHql("from CbsContractEntity where status = " + StaticValue.CBS_CONTRACT_State_1 + " " +
                "and contractType = '"+StaticValue.CBS_CONTRACT_TYPE_MB+"'");
        if(contractList != null){
            req.setAttribute("contractList", contractList);
        }*/
        return new ModelAndView ("com/zybk/cbscontract/cbsContractRealUpdate");
    }
    @RequestMapping(params = "doUpdateCancelDes")
    public void doUdpdateCancelDes(HttpServletRequest request,CbsContractEntity cbsContract) {
        CbsContractEntity t = cbsContractService.get ( CbsContractEntity.class, cbsContract.getId() );
        try {
            MyBeanUtils.copyBeanNotNull2Bean ( cbsContract, t );
            cbsContractService.saveOrUpdate ( t );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping(params = "revoke")
    public ModelAndView revoke(String id,HttpServletRequest request) {
        CbsContractEntity t = cbsContractService.get ( CbsContractEntity.class, id );
        request.setAttribute("t",t);
        return new ModelAndView ("com/zybk/cbscontract/cbsContractRevoke");
    }
    @RequestMapping(params = "delMc")
    @ResponseBody
    public AjaxJson delMc(String mid) {
        AjaxJson j = new AjaxJson();
        CbsContractMcEquipmentEntity t = cbsContractMcEquipmentServiceI.get ( CbsContractMcEquipmentEntity.class, mid );
        t.setStatus(3);
        cbsContractMcEquipmentServiceI.saveOrUpdate(t);
        j.setSuccess(true);
        return j;
    }

    /**
     * 获取可以选择合同模板列表
     * @param cbsContract
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "datagridOfContractTemplate")
    public void datagridOfContractTemplate(CbsContractEntity cbsContract, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery ( CbsContractEntity.class, dataGrid );
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql ( cq, cbsContract, request.getParameterMap () );
        try {
            //自定义追加查询条件

            //列表显示所有状态为“正常”的类型为“模板合同”的合同
            cq.add(Restrictions.eq("status", StaticValue.CBS_CONTRACT_State_1));
            cq.add(Restrictions.eq("contractType", StaticValue.CBS_CONTRACT_TYPE_MB));

        } catch (Exception e) {
            throw new BusinessException ( e.getMessage () );
        }
        cq.add ();
        this.cbsContractService.getDataGridReturn ( cq, true );
        TagUtil.datagrid ( response, dataGrid );
    }

    /**
     * 删除服务合同信息
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsContractEntity cbsContract, HttpServletRequest request) {
        AjaxJson j = new AjaxJson ();
        cbsContract = systemService.getEntity ( CbsContractEntity.class, cbsContract.getId () );
        message = "服务合同信息删除成功";
        try {
            cbsContractService.delete ( cbsContract );
            systemService.addLog ( message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO );
        } catch (Exception e) {
            e.printStackTrace ();
            message = "服务合同信息删除失败";
            throw new BusinessException ( e.getMessage () );
        }
        j.setMsg ( message );
        return j;
    }

    /**
     * 批量删除服务合同信息
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson ();
        message = "服务合同信息删除成功";
        try {
            for (String id : ids.split ( "," )) {
                CbsContractEntity cbsContract = systemService.getEntity ( CbsContractEntity.class,
                        id
                );
                cbsContractService.delete ( cbsContract );
                systemService.addLog ( message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO );
            }
        } catch (Exception e) {
            e.printStackTrace ();
            message = "服务合同信息删除失败";
            throw new BusinessException ( e.getMessage () );
        }
        j.setMsg ( message );
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView ( "com/zybk/cbscontract/cbsContractUpload" );
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public void exportXls(HttpServletRequest request, HttpServletResponse response) {
        cbsContractService.exportXls(request,response);

    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsContractEntity cbsContract, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put ( TemplateExcelConstants.FILE_NAME, "服务合同信息" );
        modelMap.put ( TemplateExcelConstants.PARAMS, new TemplateExportParams ( "Excel模板地址" ) );
        modelMap.put ( TemplateExcelConstants.MAP_DATA, null );
        modelMap.put ( TemplateExcelConstants.CLASS, CbsContractEntity.class );
        modelMap.put ( TemplateExcelConstants.LIST_DATA, null );
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson ();
        Map<String, Object> attributes = new HashMap<String, Object> ();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap ();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet ()) {
            MultipartFile file = entity.getValue ();// 获取上传文件对象
            ImportParams params = new ImportParams ();
            params.setTitleRows ( 0 );
            params.setHeadRows ( 1 );
            params.setNeedSave ( true );
            try {
                CbsContractMcEquipmentEntity e = new CbsContractMcEquipmentEntity();
                List<CbsContractMcEquipmentEntity> listCbsContractEntitys = ExcelImportUtil.importExcelByIs ( file.getInputStream (), CbsContractMcEquipmentEntity.class, params );
                List<ZyEquipmentSpareEntity> spareEntityList = zyEquipmentSpareService.findHql("from ZyEquipmentSpareEntity");
                List list1 = new ArrayList();
                List<CbsContractMcEquipmentEntity> list = cbsContractMcEquipmentServiceI.findHql("from CbsContractMcEquipmentEntity");
                List snList = new ArrayList();
                List contractCodeList = new ArrayList();;
                for(int i = 0;i<list.size();i++){
                    if(list!=null){
                        snList.add(list.get(i).getSn());
                        contractCodeList.add(list.get(i).getContractCode());
                    }
                }
                for(int i = 0;i<spareEntityList.size();i++){
                    list1.add(spareEntityList.get(i).getSn());
                }
                long time = DateUtils.getDate().getTime();
                long t= 0;
                DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                int x = 0;
                for (CbsContractMcEquipmentEntity cbsContractMcEquipmentEntity : listCbsContractEntitys) {
                    x++;
                    System.out.println(cbsContractMcEquipmentEntity.getOrderCode()+"--"+x);
                    snList.add(cbsContractMcEquipmentEntity.getSn());
                    contractCodeList.add(cbsContractMcEquipmentEntity.getContractCode());
                    //list = cbsContractMcEquipmentServiceI.findHql("from CbsContractMcEquipmentEntity");
                    /*snList.clear();
                    contractCodeList.clear();
                    for(int i = 0;i<list.size();i++){
                        if(list!=null){
                            snList.add(list.get(i).getSn());
                            contractCodeList.add(list.get(i).getContractCode());
                        }
                    }*/
                    if("".equals(cbsContractMcEquipmentEntity.getFileTurnDate())){
                        cbsContractMcEquipmentEntity.setFileTurnDate(null);
                    }
                    if("".equals(cbsContractMcEquipmentEntity.getPayDate())){
                        cbsContractMcEquipmentEntity.setPayDate(null);
                    }
                    if(cbsContractMcEquipmentEntity.getContractCode()==null|"".equals(cbsContractMcEquipmentEntity.getContractCode())){
                        String orderCode = cbsContractMcEquipmentEntity.getOrderCode();
                        String substring = "";
                        if(orderCode.contains(".")){
                            int i = orderCode.indexOf(".");
                            substring = orderCode.substring(0, i);
                        }else{
                            substring = orderCode;
                        }
                        j.setAttributes ( attributes );
                        attributes.put ( "name", file.getOriginalFilename() );
                        attributes.put ( "msg", "序号"+substring+"的维保合同编号不存在！"  );
                        t = DateUtils.getDate().getTime();
                        if(t-time>30000){
                            continue;
                        }else{
                            return j;
                        }
                    }else if(cbsContractMcEquipmentEntity.getSn()==null||!list1.contains(cbsContractMcEquipmentEntity.getSn())){
                        String orderCode = cbsContractMcEquipmentEntity.getOrderCode();
                        String substring = "";
                        if(orderCode.contains(".")){
                            int i = orderCode.indexOf(".");
                            substring = orderCode.substring(0, i);
                        }else{
                            substring = orderCode;
                        }
                        j.setAttributes ( attributes );
                        attributes.put ( "name", file.getOriginalFilename() );
                        attributes.put ( "msg", "序号"+substring+"的设备序列号不存在"  );
                        t = DateUtils.getDate().getTime();
                        if(t-time>30000){
                            continue;
                        }else{
                            return j;
                        }
                    }else if(cbsContractMcEquipmentEntity.getServiceStartDate()==null||"".equals(cbsContractMcEquipmentEntity.getServiceStartDate())||cbsContractMcEquipmentEntity.getServiceEndDate()==null||"".equals(cbsContractMcEquipmentEntity.getServiceEndDate())||df.parse(cbsContractMcEquipmentEntity.getServiceStartDate()).getTime()>df.parse(cbsContractMcEquipmentEntity.getServiceEndDate()).getTime()){
                        String orderCode = cbsContractMcEquipmentEntity.getOrderCode();
                        String substring = "";
                        if(orderCode.contains(".")){
                            int i = orderCode.indexOf(".");
                            substring = orderCode.substring(0, i);
                        }else{
                            substring = orderCode;
                        }
                        j.setAttributes ( attributes );
                        attributes.put ( "name", file.getOriginalFilename() );
                        attributes.put ( "msg", "序号"+substring+"的维保服务起止时间不正确"  );
                        t = DateUtils.getDate().getTime();
                        if(t-time>30000){
                            continue;
                        }else{
                            return j;
                        }
                    }else if(contractCodeList.contains(cbsContractMcEquipmentEntity.getContractCode())){
                        List<CbsContractMcEquipmentEntity> listbySql = cbsContractMcEquipmentServiceI.findHql("from CbsContractMcEquipmentEntity where sn ='"+cbsContractMcEquipmentEntity.getSn()+"'");
                        if(listbySql.size()!=0){
                            for(int i = 0;i<listbySql.size();i++){
                                if(listbySql.get(i).getSn().equals(cbsContractMcEquipmentEntity.getSn())&&listbySql.get(i).getContractCode().equals(cbsContractMcEquipmentEntity.getContractCode())){
                                    if(listbySql.get(i).getStatus()!=null&&listbySql.get(i).getStatus()==1){
                                        cbsContractMcEquipmentServiceI.deleteEntityById(CbsContractMcEquipmentEntity.class,listbySql.get(i).getId());
                                        cbsContractMcEquipmentEntity.setStatus(1);
                                        cbsContractMcEquipmentServiceI.save ( cbsContractMcEquipmentEntity );
                                    }else{
                                        break;
                                    }
                                }else{
                                    cbsContractMcEquipmentEntity.setStatus(1);
                                    cbsContractMcEquipmentServiceI.save ( cbsContractMcEquipmentEntity );
                                }
                            }
                            continue;
                        }
                        else{
                            cbsContractMcEquipmentEntity.setStatus(1);
                            cbsContractMcEquipmentServiceI.save ( cbsContractMcEquipmentEntity );
                        }
                    }
                    else{
                        cbsContractMcEquipmentEntity.setStatus(1);
                        cbsContractMcEquipmentServiceI.save ( cbsContractMcEquipmentEntity );
                    }
                }

                    attributes.put ( "name", file.getOriginalFilename() );
                    attributes.put ( "msg", "文件导入成功！"  );
                    j.setAttributes ( attributes );

            } catch (Exception e) {
                attributes.put ( "msg", "文件导入失败！"  );
                j.setAttributes ( attributes );
                logger.error ( ExceptionUtil.getExceptionMessage ( e ) );
            } finally {
                try {
                    file.getInputStream ().close ();
                } catch (IOException e) {
                    e.printStackTrace ();
                }
            }
        }
         return j;
    }
    /*
    * 查看合同详情
    * */
    @RequestMapping(params = "goCheck")
    public ModelAndView goCheck(HttpServletRequest req){
        String id = req.getParameter("id");
        CbsContractEntity cbsContract = null;
        if (StringUtil.isNotEmpty ( id )) {
            cbsContract = cbsContractService.getEntity ( CbsContractEntity.class, id );
            req.setAttribute ( "cbsContractPage", cbsContract );
            List<TSDepart> tsDeparts = systemService.findHql("from TSDepart where orgType = ?", StaticValue.DIC_ORG_TYPE_THIRD_PARTY);
            req.setAttribute("tsDeparts", tsDeparts);
            //SLA条款信息
            String[] slaIdsplit={};
            if(cbsContract.getSlaId()!=null){
                slaIdsplit = cbsContract.getSlaId().split(",");
            }
            String[] serviceNameSplit = {};
            if(cbsContract.getServiceName()!=null){
                serviceNameSplit = cbsContract.getServiceName().split(",");
            }
            String[] descriptionSplit = {};
            if(cbsContract.getDescription()!=null){
                descriptionSplit = cbsContract.getDescription().split(",");
            }
            String[] supplementSplit = {};
            if(cbsContract.getSupplement()!=null){
                supplementSplit = cbsContract.getSupplement().split(",");
            }
            List<CbsContractSlaEntity> slaList = systemService.findHql("from CbsContractSlaEntity where isUse = " + StaticValue.DIC_TRUE_OR_FALSE_NUM_1+"");
            List<String> slaIdListbySql = systemService.findListbySql("select cs.id from cbs_contract_sla cs LEFT JOIN sla_contract c ON cs.id=c.sla_Id LEFT JOIN cbs_contract cc ON cc.id=c.contract_id where cc.id='" + id + "'");
            req.setAttribute("slaIdListbySql", slaIdListbySql);
            List<SlaContractEntity> sItemList = systemService.findHql("from SlaContractEntity where contractId='" + id+"'");
            req.setAttribute("sItemList", sItemList);
            if(slaList != null){
                for(int i = 0;i<slaList.size();i++){
                    String serviceItem = slaList.get(i).getServiceItem();
                    slaList.get(i).setServiceItems(serviceItem.split(","));
                    for(int j = 0;j<slaIdsplit.length;j++){
                        if(slaList.get(i).getId().equals(slaIdsplit[j])){
                            slaList.get(i).setsName(serviceNameSplit[j]);
                            slaList.get(i).setDescrip(descriptionSplit[j]);
                            slaList.get(i).setSupple(supplementSplit[j]);
                        }
                    }
                }
                req.setAttribute("slaList", slaList);
            }
        }
        //MC条款信息
        List<CbsContractMcEquipmentEntity> mcList = systemService.findHql("from CbsContractMcEquipmentEntity where contractCode = '" + cbsContract.getContractCode() + "'");
        if(mcList != null){
            req.setAttribute("mcList", mcList);
        }
        for(int i = 0;i<mcList.size();i++){
            if(mcList.get(i).getStatus()!=1){
                req.setAttribute("code", 1);
            }
        }
        return new ModelAndView("com/zybk/cbscontract/cbsContractDetial");
    }

}
